
import numpy as np
import  matplotlib.pyplot as plt
import  math
from  collections import Counter
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
def knn():
    train_x=np.array([[1,1.2],[3,3.3],[5,2.2],[7,5.7],[9,8.4]]);
    train_y=np.array([0,0,0,1,1]);
    # plt.scatter(train_x[train_y==0,0],train_x[train_y==0,1],color='r',label='normal');
    # plt.scatter(train_x[train_y == 1, 0], train_x[train_y==1, 1], color='g', label='bad')
    # plt.title("sample");
    # plt.show()
    #---
    x=np.array([9,3.7]);
    plt.scatter(x[0],x[1])
    # plt.show()
    distant=[];
    for x_train in train_x:
        d=math.sqrt(np.sum((x-x_train)**2));
        distant.append(d);
    nearst=np.argsort(distant);
    k=3;
    topk_y=[train_y[i] for i in nearst[:3]];
    voutes=Counter(topk_y);
    pre=voutes.most_common(1)[0][0];
    if pre==0:
        plt.title("blue dot is recognized as red class");
    else:
        plt.title("blue dot is recongnized as green class");

    plt.scatter(train_x[train_y == 0, 0], train_x[train_y == 0, 1], color='r', label='normal');
    plt.scatter(train_x[train_y == 1, 0], train_x[train_y == 1, 1], color='g', label='bad')
    plt.scatter(x[0],x[1],color='b');
    plt.show()


if __name__ == '__main__':
    knn()